<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="兑换码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入兑换码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="套餐名称" prop="changeName">
        <el-input
          v-model="queryParams.changeName"
          placeholder="请输入套餐名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['ai:user-assets-code-usage-log:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="主键ID" align="center" prop="id" width="80px" />
      <el-table-column label="兑换码ID" align="center" prop="codeId" width="100px" />
      <el-table-column label="兑换码" align="center" prop="code" width="120px" />
      <el-table-column label="用户ID" align="center" prop="userId" width="100px" />
      <el-table-column label="使用者用户名" align="center" prop="username" width="120px" />
      <el-table-column label="用户IP" align="center" prop="userIp" width="140px" />
      <el-table-column label="用户代理" align="center" prop="userAgent" width="200px" />
      <el-table-column label="设备信息" align="center" width="200px">
        <template #default="scope">
          <div>
            <div>{{ formatDeviceInfo(scope.row.deviceInfo) }}</div>
            <el-button 
              type="text" 
              size="small" 
              @click="showDeviceDetail(scope.row.deviceInfo)"
              style="margin-top: 4px;"
            >
              查看详情
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="使用时间"
        align="center"
        prop="usageTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="获得资产" align="center" width="250px">
        <template #default="scope">
          <div>
            <div>{{ formatAssetsReceived(scope.row.assetsReceived) }}</div>
            <el-button 
              type="text" 
              size="small" 
              @click="showAssetsDetail(scope.row.assetsReceived)"
              style="margin-top: 4px;"
            >
              查看详情
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="套餐名称" align="center" prop="changeName" width="120px" />
      <el-table-column label="客户名称" align="center" prop="customerName" width="120px" />
      <el-table-column label="使用结果" align="center" prop="usageResult" width="100px">
        <template #default="scope">
          <el-tag :type="scope.row.usageResult === 1 ? 'success' : 'danger'">
            {{ scope.row.usageResult === 1 ? '成功' : '失败' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="失败原因" align="center" prop="failureReason" width="150px" />
      <el-table-column label="追踪ID" align="center" prop="traceId" width="200px" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        :formatter="dateFormatter"
        width="180px"
      />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <UserAssetsCodeUsageLogForm ref="formRef" @success="getList" />

  <!-- 详情查看弹窗 -->
  <el-dialog v-model="detailVisible" :title="detailTitle" width="60%" top="5vh">
    <el-scrollbar height="400px">
      <pre style="white-space: pre-wrap; word-wrap: break-word; font-family: monospace; font-size: 12px; line-height: 1.4;">{{ detailContent }}</pre>
    </el-scrollbar>
    <template #footer>
      <el-button @click="detailVisible = false">关闭</el-button>
      <el-button type="primary" @click="copyToClipboard">复制</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { UserAssetsCodeUsageLogApi, UserAssetsCodeUsageLogVO } from '@/api/ai/userassetscodeusagelog'
import UserAssetsCodeUsageLogForm from './UserAssetsCodeUsageLogForm.vue'

/** 兑换码使用记录 列表 */
defineOptions({ name: 'UserAssetsCodeUsageLog' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<UserAssetsCodeUsageLogVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  codeId: undefined,
  code: undefined,
  userId: undefined,
  username: undefined,
  userType: undefined,
  userIp: undefined,
  userAgent: undefined,
  deviceInfo: undefined,
  usageTime: [],
  assetsReceived: undefined,
  changeId: undefined,
  changeName: undefined,
  customerId: undefined,
  customerName: undefined,
  usageResult: undefined,
  failureReason: undefined,
  traceId: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 详情弹窗相关
const detailVisible = ref(false)
const detailTitle = ref('')
const detailContent = ref('')

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserAssetsCodeUsageLogApi.getUserAssetsCodeUsageLogPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserAssetsCodeUsageLogApi.deleteUserAssetsCodeUsageLog(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await UserAssetsCodeUsageLogApi.exportUserAssetsCodeUsageLog(queryParams)
    download.excel(data, '兑换码使用记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 格式化设备信息 */
const formatDeviceInfo = (deviceInfoStr: string) => {
  try {
    if (!deviceInfoStr) return '无设备信息'
    const deviceInfo = JSON.parse(deviceInfoStr)
    const deviceType = deviceInfo.deviceType || '未知'
    const browser = deviceInfo.browser || '未知'
    return `${deviceType} | ${browser}`
  } catch {
    return '设备信息解析失败'
  }
}

/** 格式化获得资产 */
const formatAssetsReceived = (assetsStr: string) => {
  try {
    if (!assetsStr) return '无资产信息'
    const assets = JSON.parse(assetsStr)
    const changeName = assets.changeName || '未知套餐'
    const contentDays = assets.contentDays || 0
    const simulationDays = assets.simulationDays || 0
    return `${changeName} | 内容:${contentDays}天 | 模拟:${simulationDays}天`
  } catch {
    return '资产信息解析失败'
  }
}

/** 显示设备详情 */
const showDeviceDetail = (deviceInfoStr: string) => {
  try {
    const deviceInfo = JSON.parse(deviceInfoStr)
    detailTitle.value = '设备信息详情'
    detailContent.value = JSON.stringify(deviceInfo, null, 2)
    detailVisible.value = true
  } catch {
    message.error('设备信息格式错误')
  }
}

/** 显示资产详情 */
const showAssetsDetail = (assetsStr: string) => {
  try {
    const assets = JSON.parse(assetsStr)
    detailTitle.value = '获得资产详情'
    detailContent.value = JSON.stringify(assets, null, 2)
    detailVisible.value = true
  } catch {
    message.error('资产信息格式错误')
  }
}

/** 复制到剪贴板 */
const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(detailContent.value)
    message.success('已复制到剪贴板')
  } catch {
    message.error('复制失败')
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
